<?php

declare(strict_types=1);

namespace app\service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use app\utils\Redis as RedisDB;
class JwtSerice
{
    private const SECRET_KEY = ''; // 设置密钥
    private const EXP = 60 * 60; // 设置过期时间为一小时

    /**
     * 生成token
     * @param array $payload
     * @return string
     */
    public static function creatToken(array $payload): string
    {
        $payload['exp'] = time() + (self::EXP);
        $encode = JWT::encode($payload, self::SECRET_KEY, 'HS256');
        return $encode;
    }

    /**
     * 验证token
     * @param string $token
     * @return array|bool
     */
    public static function validateToken(string $token)
    {
        try {
            $decode = JWT::decode($token, new Key(self::SECRET_KEY, 'HS256'));
            return (array) $decode;
        } catch (ExpiredException $e) {
            // Token 已过期，但仍可获取 Payload
            $info = (array) $e->getPayload();
            $info['exp'] = 0;
            return $info;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 设置token
     * @param string $uid
     * @param string $token
     * @return string
     */
    public static function setToken($uid, $token)
    {
        $redis = new RedisDB('user');
        $newToken = self::creatToken([
            'uid' => $uid,
            'token' => $token
        ]);
        // cache('uid' . $uid, $token, self::EXP);
        $redis->set("token:$uid", (string) $token, self::EXP);
        $infoStatus = $redis->exists("info:$uid");
        $roleStatus = $redis->exists("role:$uid");
        if ($infoStatus && $roleStatus) {
            $redis->expire("info:$uid", self::EXP);
            $redis->expire("role:$uid", self::EXP);
        }
        return $newToken;
    }

    /**
     * 删除token
     * @param string $uid
     */
    public static function delToken($uid)
    {
        RedisDB::delKey('user', "token:$uid");
        // cache('uid' . $uid, NULL);
    }
}
